package com.example.canteeradiodemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import javax.security.auth.login.LoginException;

public class MainActivity extends AppCompatActivity {
    private ImageView iv_horn;
    private TextView tv_left_content,tv_right_content;
    private MyBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
            }
    private void init() {
        iv_horn = findViewById(R.id.iv_horn);
        tv_left_content = findViewById(R.id.tv_left_content);
        tv_right_content = findViewById(R.id.tv_right_content);
        receiver = new MyBroadcastReceiver();
        String action = "Open_Rice";
        IntentFilter intentFilter = new IntentFilter(action);
        registerReceiver(receiver, intentFilter);
        iv_horn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_right_content.setText("开饭了!");
                Intent intent = new Intent();
                intent.setAction("Open_Rice");
                sendBroadcast(intent);
            }

        });
    }
    class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO 1 处理接收到的广播信息
            if (intent.getAction().equals("Open_Rice")) {
                tv_left_content.setVisibility(View.VISIBLE);
                Log.i("MyBroadcastReceiver", "自定义的广播接受者,接到了发送开饭信号的广播消息");
            }
            Log.i("MyBroadcastReceiver", intent.getAction());
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // TODO 4 注销广播
        unregisterReceiver(receiver);
    }
}